package ewu
import ewu._

/**
 * Diese Klasse stellt den Substraktionsoperator zur Verfuegung.
 * Es werden die beiden Expressions "left" sowie "right"
 * verwendet.
 * Beispiel: left - right
 */

case class Minus(left: Expression,
                 right: Expression) extends Operator {
  def evaluate(env: Environment): Option[BigInt]
  = (left.evaluate(env), right.evaluate(env)) match {
    case (Some(le), Some(ri)) => Some(le - ri)
    case _ => None
  }

  override def toString: String = left + "-" + toString(right)

  private def toString (e: Expression) = e match{
    case _: Plus  => "(" + e + ")"
    case _: Minus => "(" + e + ")"
    case _        => e
  }

  def reduce: Expression = (left.reduce, right.reduce) match {
    case (e, n: Number) if n == 0 => e
    case (le: Number, ri: Number) => Number(le.value - ri.value)
    case (e, ri: Number)          => Plus(e, Number(- ri.value))
    case (le, ri) if le equals ri => Number(0)
    case (le, ri)                 => Minus(le, ri)
  }
}